﻿/* Copyright (c) 2001-2009, The HSQL Development Group
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * Neither the name of the HSQL Development Group nor the names of its
 * contributors may be used to endorse or promote products derived from this
 * software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL HSQL DEVELOPMENT GROUP, HSQLDB.ORG,
 * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Resources;
using EffiProz.Core.Lib;
using EffiProz.Core.Results;

namespace EffiProz.Core.Errors
{
    /**
 * Contains static factory methods to produce instances of HsqlException
 *
 * @author Loic Lefevre
 * @author Fred Toussi (fredt@users dot sourceforge.net)
 * @version 1.9.0
 * @since 1.9.0
 */
    public class Error
    {

        //
        public static bool TRACE = false;
        public static bool TRACESYSTEMOUT = false;

        //
        private static String errPropsName = "sql-state-messages";
        private static int bundleHandle =
            BundleHandler.getBundleHandle(errPropsName, null);
        private static String MESSAGE_TAG = "$$";
        private static int SQL_STATE_DIGITS = 5;
        private static int SQL_CODE_DIGITS = 4;
        private static int ERROR_CODE_BASE = 11;

        public static Exception runtimeError(int code, String add)
        {

            CoreException e = error(code, add);

            return new Exception(e.getMessage());
        }

        public static CoreException error(int code, String add)
        {

            String s = getMessage(code);

            if (add != null)
            {
                s += ": " + add;
            }

            return new CoreException(null, s.Substring(SQL_STATE_DIGITS + 1),
                                     s.Substring(0, SQL_STATE_DIGITS), -code);
        }

        public static CoreException error(int code)
        {
            return error(null, code, 0, null);
        }

        public static CoreException error(int code, Exception t)
        {

            String message = getMessage(code, 0, null);

            return new CoreException(t, message.Substring(0, SQL_STATE_DIGITS),
                                     -code);
        }

        /**
         * Compose error message by inserting the strings in the add parameters
         * in placeholders within the error message. The message string contains
         * $$ markers for each context variable. Context variables are supplied in
         * the add parameters.
         *
         * @param code      main error code
         * @param subCode   sub error code (if 0 => no subMessage!)
         * @param   add     optional parameters
         *
         * @return an <code>HsqlException</code>
         */
        public static CoreException error(Exception t, int code, int subCode,
                                           Object[] add)
        {

            String message = getMessage(code, subCode, add);
            int sqlCode = subCode < ERROR_CODE_BASE ? code
                                                       : subCode;

            if (t != null)
            {
                return new CoreException(t, message.Substring(SQL_STATE_DIGITS + 1),
                                         message.Substring(0, SQL_STATE_DIGITS),
                                         -sqlCode);
            }
            else
            {
                return new CoreException( message.Substring(SQL_STATE_DIGITS + 1),
                                         message.Substring(0, SQL_STATE_DIGITS),
                                         -sqlCode);
            }

        }

        public static CoreException error(int code, int code2)
        {
            return error(code, getMessage(code2));
        }

        /**
         * Compose error
         * in placeholders within the error message. The message string contains
         * $$ markers for each context variable. Context variables are supplied in
         * the add parameters.
         *
         * @see HsqlException#HsqlException(String, String, int)
         * @return an <code>HsqlException</code>
         */
        public static CoreException error(String message, String sqlState, int i)
        {
            return new CoreException(null, message, sqlState, i);
        }

        /**
         * Compose error message by inserting the strings in the add variables
         * in placeholders within the error message. The message string contains
         * $$ markers for each context variable. Context variables are supplied in
         * the add parameter. (by Loic Lefevre)
         *
         * @param message  message string
         * @param add      optional parameters
         *
         * @return an <code>HsqlException</code>
         */
        private static String insertStrings(String message, Object[] add)
        {

            StringBuilder sb = new StringBuilder(message.Length + 32);
            int lastIndex = 0;
            int escIndex = message.Length;

            // removed test: i < add.length
            // because if mainErrorMessage is equal to "blabla $$"
            // then the statement escIndex = mainErrorMessage.length();
            // is never reached!  ???
            for (int i = 0; i < add.Length; i++)
            {
                escIndex = message.IndexOf(MESSAGE_TAG, lastIndex);

                if (escIndex == -1)
                {
                    break;
                }

                sb.Append(message.Substring(lastIndex, escIndex - lastIndex));
                sb.Append(add[i] == null ? "null exception message"
                                         : add[i].ToString());

                lastIndex = escIndex + MESSAGE_TAG.Length;
            }

            escIndex = message.Length;

            sb.Append(message.Substring(lastIndex, escIndex - lastIndex));

            return sb.ToString();
        }

        /**
         * Returns the error message given the error code.<br/>
         * This method is be used when throwing exception other
         * than <code>HsqlException</code>.
         *
         * @param errorCode    the error code associated to the error message
         * @return  the error message associated with the error code
         */
        public static String getMessage(int errorCode)
        {
            return getMessage(errorCode, 0, null);
        }

        /**
         * Returns the error SQL STATE sting given the error code.<br/>
         * This method is be used when throwing exception based on other exceptions.
         *
         * @param errorCode    the error code associated to the error message
         * @return  the error message associated with the error code
         */
        public static String getStateString(int errorCode)
        {
            return getMessage(errorCode, 0, null).Substring(0, SQL_STATE_DIGITS);
        }

        /**
         * Returns the error message given the error code.<br/> This method is used
         * when throwing exception other than <code>HsqlException</code>.
         *
         * @param code the code for the error message
         * @param subCode the code for the addon message
         * @param add value(s) to use to replace the placeholer(s)
         * @return the error message associated with the error code
         */
        public static String getMessage(int code, int subCode,
                                        Object[] add)
        {

            String message = getResourceString(code);

            if (subCode != 0)
            {
                message += getResourceString(subCode);
            }

            if (add != null)
            {
                message = insertStrings(message, add);
            }

            return message;
        }

        private static String getResourceString(int code)
        {

            String key = StringUtil.toZeroPaddedString(code, SQL_CODE_DIGITS,
                SQL_CODE_DIGITS);

            return BundleHandler.getString(bundleHandle,"E"+ key);
        }

        public static CoreException error(Result result)
        {
            return new CoreException(result);
        }

        /**
         * Used to print messages to System.out
         *
         *
         * @param message message to print
         */
        public static void printSystemOut(String message)
        {

            if (TRACESYSTEMOUT)
            {
                System.Diagnostics.Debug.WriteLine(message);
            }
        }
    }
}
